package com.le.tester.tip;

import java.util.Objects;

/**
 * createTime：2022/2/9 15:25
 * description：多个线程进行顺序执行,使用join
 */
public class MultiThreadOrderExecWithJoin {

    //join使用的方法，在当前线程B中，线程A使用join，线程A先执行完毕，再执行线程b

    public static void main(String[] args) {
        Thread t1 = new Thread(new Work(null), "线程t1");
        //在t2的线程中执行t1，t1需要join，等待t1执行完了再执行t2
        Thread t2 = new Thread(new Work(t1), "线程t2");
        Thread t3 = new Thread(new Work(t2), "线程t3");

        t1.start();
        t2.start();
        t3.start();
    }

    static class Work implements Runnable {

        private Thread beforeThread;

        public Work(Thread beforeThread) {
            this.beforeThread = beforeThread;
        }

        @Override
        public void run() {
            if (Objects.nonNull(beforeThread)) {
                try {
                    beforeThread.join();
                    System.out.println("Thread start:" + Thread.currentThread().getName());
                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage());
                }
            } else {
                System.out.println("Thread start:" + Thread.currentThread().getName());
            }
        }
    }
}
